﻿using Microsoft.Playwright;
using Newtonsoft.Json.Linq;
using OnlineStore.Common;
using System;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;

namespace OnlineStore
{
    public class TaoBaoPlayer: Player
    {
        public TaoBaoPlayer(PlayerTask playerTask, ExecuteStatus status) : base(playerTask, status) { }

        public override async Task Execute(IBrowser browser)
        {
            try
            {
                await new TaoBaoReceiver(this).Execute(browser);
            }
            catch (Exception e)
            {
                DetailedAction($"【Erro: {e.Message}】");
                throw;
            }
            finally 
            {
                if (this.UsedTitles.Count > 0)
                {
                    int usedCount;
                    if (this.UsedTitles.Count == 0)
                    {
                        usedCount = 0;
                    }
                    else 
                    {
                        usedCount = this.UsedTitles.Count - 6;
                    }
                    DetailedAction("*********************【开始写入】*********************");
                    DetailedAction($"已用标题: {usedCount}");
                    string info =
                        $"已用标题 UsedTitles: {usedCount} \n" +
                        $"剩余标题 CarMap: {this.CarMap.Count} \n" +
                        $"===============================================================";
                    this.UsedTitles.Add(info);
                    // 写入上版日志
                    ParseFile.AppenListToFile(this.LogPath, this.UsedTitles);

                    if (this.CarMap.Count > 0)
                    {
                        DetailedAction($"剩余标题: {this.CarMap.Count}");
                        // 写入剩余标题
                        ParseFile.WriteListToFile(this.TitlePath, this.CarMap.Values.ToList<string>());
                    }
                    else
                    {
                        File.Delete(this.TitlePath);
                        string tempPath = this.TitlePath.Replace(".txt", "(已完成任务).txt");
                        ParseFile.WriteListToFile(tempPath, this.CarMap.Values.ToList<string>());
                    }
                    DetailedAction("*********************【写入完毕】*********************");
                }
            }
        }
    }
}
